﻿using System;
using System.Threading;
using System.Windows.Threading;

namespace Com.PhilChuang.Utils.Mobile
{
	public abstract class SilverlightServiceLocatorBase : ServiceLocatorBase
	{
		public Dispatcher Dispatcher { get; set; }

		protected override Func<Type, object> DefaultInitializer
		{
			get
			{
				return (t) =>
				{
					// default initialization
					if (!t.IsSubclassOf (typeof (System.Windows.Controls.Control)))
						return CreateInstance (t);

					// it's an UI object, make sure it gets created on the right thread
					Object impl = null;
					var mre = new ManualResetEvent (false);
					this.Dispatcher.BeginInvoke (
						() =>
						{
							impl = CreateInstance (t);
							mre.Set ();
						});
					mre.WaitOne ();
					return impl;
				};
			}
		}

		protected virtual Object CreateInstance (Type t)
		{
			//var thisType = GetType ();
			//var thisAssembly = thisType.Assembly;
			//return thisAssembly.CreateInstance (t.AssemblyQualifiedName);

			return Activator.CreateInstance (t);
		}
	}
}
